import uuid

from django.db import models
from django.urls import reverse

# Create your models here.

class PostList(models.Model):
    id = models.CharField(max_length=128, primary_key=True, verbose_name='Id')
    title = models.CharField(max_length=30, verbose_name='标题')
    user = models.ForeignKey('user.User', db_column='user', on_delete=models.CASCADE, verbose_name='用户')
    like_count = models.IntegerField(default=0, verbose_name='收藏次数')
    share_count = models.IntegerField(default=0, verbose_name='分享次数')
    category = models.ForeignKey('PostCategory', on_delete=models.DO_NOTHING, db_column='category', verbose_name='主题类型')
    content = models.TextField(verbose_name='内容')
    summary = models.CharField(max_length=200, blank=True, verbose_name='简介')
    publish_time = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')

    class Meta:
        managed = True
        verbose_name = '主题帖列表'
        verbose_name_plural = verbose_name
        db_table = 'post_list'

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.id:
            self.id = uuid.uuid4()
        if not self.summary:
            if len(self.content) > 80:
                self.summary = self.content[:80] + '...'
            else:
                self.summary = self.content
        super(PostList, self).save()

    def update(self, *args, **kwargs):
        if self.like_count:
            self.like_count = self.like_count
        super(PostList, self).save()

    def get_absolute_url(self):
        return reverse('post:post_detail', kwargs={'pk': self.id})


class PostCategory(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='类型Id')
    name = models.CharField(max_length=20, verbose_name='类型名称')

    class Meta:
        managed = True
        verbose_name = '主题帖类别'
        verbose_name_plural = verbose_name
        db_table = 'post_category'

    def __str__(self):
        return self.name
